//
//  amazon_call.m
//  amazon_test
//
//  Created by Pierre Guilbert on 7/27/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AmazonModule.h" 
#pragma mark TableView data source methods

@implementation AmazonModule

- (id)initWithStrTitle: (NSString *)inString {
	if (self = [super init])
    {
		search = [inString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		[self setItemNode];
		[self initImage];
		[self setDirectorsFromItemNode];
		[self setYearFromItemNode];
		[self setActorsFromItemNode];
		[self setTitleFromItemNode];
		
    }
	return self;
}

- (id)init {
    return [self initWithStrTitle:nil];	
}



- (NSString *)stringForPath: (NSString *)xpath ofNode:(NSXMLNode *)no { 
    NSError *error; 
    NSArray *nodes = [no nodesForXPath:xpath error:&error]; 
    if (!nodes) { 
        NSAlert *alert = [NSAlert alertWithError:error]; 
        [alert runModal]; 
        return nil; 
    } 
    if ([nodes count] == 0) { 
        return nil;
    } else { 
        return [[nodes objectAtIndex:0] stringValue]; 
    } 
} 

- (void)setItemNode {
	
	// here we build the url request for amazon

    NSString *urlString = [NSString  stringWithFormat: 
						   @"http://webservices.amazon.com/onca/xml?"
						   @"Service=AWSECommerceService&"
						   @"SubscriptionId=%@&"
						   @"Operation=ItemSearch&"
						   @"Keywords=%@&"
						   @"SearchIndex=DVD",
						   AWS_ID,
						   search];


	NSURL *url = [NSURL URLWithString:urlString]; 


	//NSLog(urlString);
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url 
											 cachePolicy:NSURLRequestReturnCacheDataElseLoad 
											 timeoutInterval:30];
	

	//-------------------------------------------------------------------------
	// Fetch the XML response 
	NSData *urlData; 
	NSURLResponse *response; 
	NSError *error; 


	urlData = [NSURLConnection sendSynchronousRequest:urlRequest 
								returningResponse:&response 
								error:&error];

	if (!urlData) { 
		NSAlert *alert = [NSAlert alertWithError:error]; 
		[alert runModal]; 
		return; 
	} 
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	// Parse the XML response from Data
	[doc release]; 
	doc = [[NSXMLDocument alloc] initWithData:urlData 
									  options:0 
										error:&error];

	
	//NSLog(@"doc = %@", doc); 
	if (!doc) { 
		NSAlert *alert = [NSAlert alertWithError:error]; 
		[alert runModal]; 
		return; 
	} 
	//-------------------------------------------------------------------------
	
	//-------------------------------------------------------------------------
	// create the itemNodes
	[itemNodes release]; 
	itemNodes = [[doc nodesForXPath:@"ItemSearchResponse/Items/Item" 
							  error:&error] retain]; 
	if (!itemNodes) { 
		NSAlert *alert = [NSAlert alertWithError:error]; 
		[alert runModal]; 
		return; 
	}
	// set asin number
    asin = [self stringForPath:@"asin"
					   ofNode:[itemNodes objectAtIndex:0]];
	if (asin == NULL)
		asin = [self stringForPath:@"ASIN"
							ofNode:[itemNodes objectAtIndex:0]];
//	NSLog(@"asin number %@", asin);


	return;
}

-(int)numberOfRowsInTableView:(NSTableView*)tv {
	return [itemNodes count];
}

- (void)initImage{


	imageData = [NSString stringWithFormat:
						  @"%@%@%@",
						  THUMB_URL,
						  asin,
						  THUMB_FORMAT];


}

- (void)setDirectorsFromItemNode {

	directors = [self stringForPath:@"ItemAttributes/Director"
							 ofNode:[itemNodes objectAtIndex:0]];
	if (directors == NULL)
		directors = [[NSString alloc] initWithString:@""];
}

- (void)setYearFromItemNode {

	year = [self stringForPath:@"ItemAttributes/ReleaseDate"
							 ofNode:[itemNodes objectAtIndex:0]];
	if (year == NULL)
		year = [[NSString alloc] initWithString:@""];
}

- (void)setActorsFromItemNode {

	NSError *error; 
    NSArray *nodes = [[itemNodes objectAtIndex:0] nodesForXPath:@"ItemAttributes/Actor" error:&error];

	NSMutableString *tmp = [[NSMutableString alloc] initWithString:[[nodes objectAtIndex:0] stringValue]];
	

	int i = 1;
	for (; i < [nodes count]; ++i)
	{

		[tmp appendFormat:@", "];
		[tmp appendFormat:(@"%@",[[nodes objectAtIndex:i] stringValue])];
	}
	
	
	if (tmp == NULL)
		actors = [[NSString alloc] initWithString:@""];
	else
		actors = [[NSString alloc] initWithString:tmp];

//	[tmp release];
}

- (void)setTitleFromItemNode {

	title = [self stringForPath:@"ItemAttributes/Title"
							 ofNode:[itemNodes objectAtIndex:0]];
	if (title == NULL)
		title = [[NSString alloc] initWithString:@""];
}

- (void) dealloc {

	[title release];
	[actors release];
	[year release];
	[directors release];
	[imageData release];
	[search release];
	[asin release];
	[super dealloc];
}

- (NSString*) getTitle{
	return title;
}
- (NSString*) getYear{
	return year;
}
- (NSString*) getImageData{
	return imageData;
}
- (NSString*) getDirectors{
	return directors;
}
- (NSString*) getActors{
	return actors;
}

@end
